package com.hqs.rxjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import com.hqs.common.utils.Log;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

public class DoubleClickActivity extends AppCompatActivity {

    @BindView(R.id.button)
    Button button;

    @BindView(R.id.tv_result)
    TextView tvResult;

    private Disposable disposable;
    private int clickNum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_double_click);

        ButterKnife.bind(this);
    }

    @OnClick(R.id.button)
    void onClick(){
        clickNum += 1;
        if(disposable == null){
            Observable.interval(100, TimeUnit.MILLISECONDS)
                    .map(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@NonNull Object o) throws Exception {
                            return clickNum;
                        }
                    })
                    .buffer(400, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<Integer>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    disposable = d;
                }

                @Override
                public void onNext(@NonNull List<Integer> integers) {
                    Log.print(integers);
                    if (integers.get(integers.size() - 1) == 2){
                        tvResult.setText("double click");
                    }
                    else{
                        tvResult.setText("not double click ");
                    }
                    clickNum = 0;
                    disposable.dispose();
                    disposable = null;
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null){
            disposable.dispose();
        }
    }
}
